package com.example.administrator.service;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.administrator.music.Main2Activity;

import java.util.Calendar;

public class MainActivity extends Activity implements View.OnClickListener {
    private static MainActivity appRef = null;
    private Button b_call_service,b_exit_service;
    private Button nextbtn = null;
    boolean k = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appRef = this;
        setContentView(R.layout.activity_main);

        b_call_service = (Button)findViewById(R.id.alarmActive);
        b_call_service.setOnClickListener(this);
        b_exit_service = (Button)findViewById(R.id.exit);
        b_exit_service.setOnClickListener(this);

        nextbtn = (Button)findViewById(R.id.nextEx);
        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);
            }
        });
    }

    public static MainActivity getApp() {
        return appRef;
    }

    public void btEvent(String data) {
        setTitle(data);
    }

    @Override
    public void onClick(View v) {
        if(v == b_call_service)
        {
            setTitle("Waiting...Alarm = 2s");
            Intent intent = new Intent(MainActivity.this,AlarmRecevier.class);
            //PendingIntent.getBroadcast()通过广播来实现闹钟提示
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this,0,intent,0);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND,2);

            // Schedule the alarm!
            /**
             * AlarmManager在规定的时间间隔到了后实现提醒服务，使用的是系统自带的service
             * 第一个参数表示闹钟类型：当系统进入睡眠状态时，这种类型的闹铃也会唤醒系统。
             * 第二个参数表示闹钟执行时间。
             * 第三个参数表示闹钟响应动作。
             */
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),p_intent);
        }

        if(v == b_exit_service)
        {
            Intent intent = new Intent(MainActivity.this,AlarmRecevier.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this,0,intent,0);
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(p_intent);
            finish();
        }
    }
}
